//
//  HOPPhotoBrowserController.swift
//  WB01
//
//  Created by HOP on 16/1/1.
//  Copyright © 2016年 HOP. All rights reserved.
//

import UIKit

import SVProgressHUD

class HOPPhotoBrowserController: UIViewController {
    // MARK: - 属性
    /// 选中的indexPath

    private var selectedIndexPath: NSIndexPath
    // cell间距
    private let CellMargin: CGFloat = 10
    /// 大图的url数组
    private var models: [HOPPhotoBrowserModal]
    /// collectionView的布局
    private let layout = UICollectionViewFlowLayout()
    /// 重用表示
    private let ReuseIdentifier = "ReuseIdentifier"
    init(indexPath: NSIndexPath, models: [HOPPhotoBrowserModal]) {
    self.selectedIndexPath = indexPath
    self.models = models
    super.init(nibName: nil, bundle: nil)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
      prepareUI()
       // 设置页码
//    pageLabel.text = "5 / 9"
    }
     // 点击哪一张,进入图片浏览器就显示哪一张
    override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
        // 如果collectioView使用autoLayout约束的是滚不动的,改成frame来设置宽高
        // 让collectionView滚动到指定的张数
        collectionView.scrollToItemAtIndexPath(selectedIndexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        // 设置页码
        setPageNum(selectedIndexPath.item + 1)
    }
    private func setPageNum(currentPage: Int) {
    pageLabel.text = "\(currentPage) / \(models.count)"
    }
    // 准备UI
    private func prepareUI() {
    // 添加子控件
       view.addSubview(collectionView)
        view.addSubview(pageLabel)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
        // 添加约束
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        pageLabel.translatesAutoresizingMaskIntoConstraints = false
        closeButton.translatesAutoresizingMaskIntoConstraints = false
        saveButton.translatesAutoresizingMaskIntoConstraints = false
        // collectionView填充父控件
//        collectionView.frame = view.bounds
        collectionView.frame = CGRect(x: 0, y: 0, width: view.bounds.width + CellMargin, height: view.bounds.height)
//    view.addConstraints( NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cv" : collectionView]))
//    view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cv" : collectionView]))
        // 页码
        // 水平centerX和父控件的centerX重合
        
        view.addConstraint(NSLayoutConstraint(item: pageLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        // 垂直距离父控件顶部20
        view.addConstraint(NSLayoutConstraint(item: pageLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 20))
        // 关闭按钮的垂直方向,距离父控件底部8
       view.addConstraints( NSLayoutConstraint.constraintsWithVisualFormat("V:[cb(35)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cb" : closeButton]))
         // 保存按钮的垂直方向,距离父控件底部8
        view.addConstraints( NSLayoutConstraint.constraintsWithVisualFormat("V:[sb(35)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["sb" : saveButton]))
        // 水平方向
        // 1.关闭按钮距离父控件左边8
        // 2.关闭按钮宽度75
        // 3.关闭按钮和保存按钮的间距>0
        // 4.保存按钮距离父控件右边8
        // 5.保存按钮宽度75
    view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-8-[cb(75)]-(>=0)-[sb(75)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cb" : closeButton,"sb" : saveButton]))
        setupCollectionView()
        
        
    }
    /// 设置collectionView
    private func setupCollectionView() {
    // 注册cell
    collectionView.registerClass(HOPPhotoBrowserCell.self, forCellWithReuseIdentifier: ReuseIdentifier)
        // 设置数据源和代理
        collectionView.dataSource = self
        collectionView.delegate = self
        // 设置cell大小,大小和屏幕一样大
        layout.itemSize = UIScreen.mainScreen().bounds.size
        // 水平滚动
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        // 分页
        collectionView.pagingEnabled = true
        // 间距
        layout.minimumInteritemSpacing = CellMargin
        layout.minimumLineSpacing = CellMargin
        // 取消弹簧效果
        collectionView.bounces = false
        
        // 取消滚动条
        collectionView.showsHorizontalScrollIndicator = false
         // 最后一个cell会显示间距,因为collectionView的最后一个cell右边和collectionView右边对齐,需要将最后一个cell往左边顶一个间距
        collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: CellMargin)
    
    }
    // MARK: - 按钮点击事件
    /// 关闭控制器
    func close() {
    dismissViewControllerAnimated(true, completion: nil)
    
    
    }
     /// 保存图片
    func save() {
    // 1获取正在显示的cell
        let cell = collectionView.cellForItemAtIndexPath(selectedIndexPath) as! HOPPhotoBrowserCell
        // 2.获取正在显示的image
        if let image = cell.imageView.image {
            // 3.保存
            // image: 要保存的图片
            // completionTarget: 保存图片后回调对象
            // completionSelector: 保存图片后回调的方法
            // - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
        
        } else {
        SVProgressHUD.showErrorWithStatus("没有图片")
        
        }
    }
    /// 保存图片后的回调
    func image(image: UIImage, didFinishSavingWithError error: NSError?,
        contextInfo: AnyObject) {
            if error != nil {
            SVProgressHUD.showErrorWithStatus("保存图片出错")
            
            } else {
            SVProgressHUD.showSuccessWithStatus("保存图片成功")
            
            }
    
      }
    // MARK: - 懒加载
    /// collectionView
     lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.layout)
    /// 显示页数的label
    private lazy var pageLabel: UILabel =  {
    let pageLabel = UILabel()
     pageLabel.font = UIFont.systemFontOfSize(13)
        pageLabel.textColor = UIColor.whiteColor()
    return pageLabel
    }()
    /// 关闭按钮
    
    private lazy var closeButton: UIButton = {
    let button = UIButton()
      // 设置文字
        button.setTitle("关闭", forState: UIControlState.Normal)
        // 设置按钮背景
        button.setBackgroundImage(UIImage(named: "health_button_orange_line"), forState: UIControlState.Normal)
    button.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
        return button
    }()
    
    /// 保存按钮
    private lazy var saveButton: UIButton = {
        let button = UIButton()
        // 设置文字
        button.setTitle("保存", forState: UIControlState.Normal)
        // 设置按钮背景
        button.setBackgroundImage(UIImage(named: "health_button_orange_line"), forState: UIControlState.Normal)
        button.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
        return button
    }()
 }

// MARK: - 扩展 CZPhotoBrowserController 实现 UICollectionViewDataSource 数据源
extension HOPPhotoBrowserController: UICollectionViewDataSource,UICollectionViewDelegate {
/// 返回cell数量
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return models.count
    }
/// 返回cell
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! HOPPhotoBrowserCell
        // 设置cell的背景
        cell.backgroundColor = UIColor.randomColor()
        // 给cell设置要显示图片的url
        // 获取模型
        let model = models[indexPath.item]
        cell.imageURL = model.largeURL
        return cell
    }
// 监听collectionView停止滚动
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        // 通过collectionView的偏移值来计算
        let index = Int(scrollView.contentOffset.x / scrollView.bounds.width)
         // 重新设置显示的页数
        setPageNum(index + 1)
    }
}
 /// 实现modal的动画
extension HOPPhotoBrowserController: UIViewControllerTransitioningDelegate {
 // 返回一个控制modal的动画对象
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return HOPPhotoBrowserModalAnimation()
    }
// 返回一个控制dismiss的动画对象

    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return HOPPhotoBrowserDismissAnimation()
    }

}
// 扩展 CZPhotoBrowserController 转场动画相关的元素

extension HOPPhotoBrowserController {
/// 生成modal时的过度视图
    func modelTempImageView() -> UIImageView {
    // 创建过度视图
    let tempImageView = UIImageView()
    // 获取到对应的模型
        let model = models[selectedIndexPath.item]
    // 获取缩略图iamgeView
    let imageView = model.imageView!
        // 设置过度视图的image
        tempImageView.image = imageView.image
        // 设置缩放模式
        tempImageView.contentMode = UIViewContentMode.ScaleAspectFill
        tempImageView.clipsToBounds = true
        // 坐标系转换
        // 从imageView.superview的坐标系转换到 toCoordinateSpace 坐标系
        // Rect: 要转换的frame
        let newFrame = imageView.superview!.convertRect(imageView.frame, toCoordinateSpace: view)
        print("imageView.frame： \(newFrame)")
        print("ima: ]\(imageView.frame)")
        // 设置frame
        tempImageView.frame = newFrame
        return tempImageView
    }
// 计算modal的最终位置
    func modalTargetRect() -> CGRect {
    // 这个时候大图不一定有,我可以拿小图来计算,新浪小图和大图的长宽比是一样地
    let model = models[selectedIndexPath.item]
    // 获取缩略图,不能强制拆包,如果没有图片,就不计算大小
        if let image = model.imageView?.image {
        let newWidth = UIScreen.mainScreen().bounds.width
          // 新的高度 / 新的宽度 = 老的高度 / 老的宽度
        let newHeight = newWidth * image.size.height / image.size.width
            var offsetY: CGFloat = 0
            // 判断是长图还是短图
            if newHeight < UIScreen.mainScreen().bounds.height {
            // 短图
            offsetY = (UIScreen.mainScreen().bounds.height - newHeight) * 0.5
            
            
            } else {
            }
            return CGRect(x: 0, y: offsetY, width: newWidth, height: newHeight)
        }
    return CGRectZero
    }
    /// dismiss时的过渡视图
    func dismissTempImageView() -> UIImageView {
    // 创建过渡视图
        let tempImageView = UIImageView()
    // 获取到正在显示的cell
    let cell = collectionView.cellForItemAtIndexPath(selectedIndexPath) as! HOPPhotoBrowserCell
    // 获取到正在显示的image
        if let image = cell.imageView.image {
        // 设置过渡视图的image
        tempImageView.image = image
        // 设置过渡视图的frame
        let newFrame = cell.imageView.superview!.convertRect(cell.imageView.frame, toCoordinateSpace: view)
            tempImageView.frame = newFrame
            // 设置填充模式
            tempImageView.contentMode = UIViewContentMode.ScaleAspectFill
            tempImageView.clipsToBounds = true
        }
    
     // 返回
    return tempImageView
    
    }
    /// 返回dismiss时的目标frame
    func dismissTargetRect() -> CGRect {
    // 获取到对应的模型
    let model = models[selectedIndexPath.item]
    // 获取缩略图
    let imageView = model.imageView!
        // 转换坐标系,从imageView的父控件转换到屏幕的左上角
        let newFrame = imageView.superview!.convertRect(imageView.frame, toCoordinateSpace: view)
        // 获取缩略图的frame
        return newFrame
    }
 }


























